import Common from "../Common/Common";
import EnumData from "../Common/EnumData";
import MyEventListener from "../Common/myEventManger/MyEventListener";
import DataManager from "../core/DataManager";
import ResourcesManager from "../core/ResourcesManager";

cc.Class({
    extends: cc.Component,

    properties: {
        puzzleType: {
            default: EnumData.PuzzleType.Button,
            type: EnumData.PuzzleType,
            tooltip: '拼图类型'
        },

        icon: {
            default: null,
            type: cc.Sprite,
            tooltip: '拼图按钮图片'
        },
        bg:{
            default: null,
            type: cc.Sprite,
            tooltip: '拼图背景图片'
        }
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start() {
    
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);

        // this.basePos = this.node.getPosition();

    },

    onDestroy() {
        this.node.off(cc.Node.EventType.TOUCH_START, this.onTouchStart);
        this.node.off(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove);
        this.node.off(cc.Node.EventType.TOUCH_END, this.onTouchEnd);
        this.node.off(cc.Node.EventType.TOUCH_CANCEL, this.onTouchEnd);
    },
    init(data) {
        if (!data) {
            return;
        }
        this.puzzleData = data;
        this.bg.spriteFrame = this.icon.spriteFrame = DataManager.GameConfig[DataManager.currLevel][this.puzzleData.dino];
        this.icon.node.active = true;
        this.bg.node.active = false;
        this.node.active = true;
        
        this.basePos = this.node.getPosition() ;
    },
    
    onTouchStart(event) {
        event.stopPropagation();
        this.icon.node.active =false;
        this.bg.node.active =true;
    },
    onTouchMove(event) {
        event.stopPropagation();
        var move_x = event.touch._point.x - event.touch._prevPoint.x;
        var move_y = event.touch._point.y - event.touch._prevPoint.y;
   
        event.target.x += move_x;
        event.target.y += move_y;
    
    },
    onTouchEnd(event) {
        event.stopPropagation();

        let checkData = {
            type: this.puzzleType,
            puzzleData: this.puzzleData,
            pos: event.target.parent.convertToWorldSpaceAR(event.target.getPosition()),
            cb: this.checkResult.bind(this)
        }
        
        MyEventListener.emit(EnumData.EventType.CheckPuzzle, checkData);
    },

    checkResult(param) {
        this.icon.node.active =true;
        this.bg.node.active =false;
        this.node.setPosition(this.basePos);
        this.node.active = param ? false : true;
        if(!this.node.active)ResourcesManager.putObjToPool("putItems",this.node)
    }

    // update (dt) {},
});
